#!/usr/bin/env python2.5
# encoding: utf-8
"""
StreamLoader.py

Created by Alakazam on 2007-07-05.
Copyright (c) 2007 . All rights reserved.
"""

import sys, os, re

class StreamLoader(object):
  def __init__(self, newStream, sourceFile):
    self.file = file(sourceFile)
    self.streams = []
    self.newStream = newStream
    self.initIterable()
  
  def initIterable(self):
    """This function must be overridden.
      It must initialize self.iterable.
      The first line returned by this iterable must contain names and types for the streams :
      
      For example for a CSV, the first line should be of the form
      startTime;endTime;stream1Name (stream1Type);stream2Name (stream2Type);"""
    self.iterable = None
  
  def run(self):
    for values in self.iterable:
      if len(self.streams):
        # We already have streams
        self.insertIntoStreams(values)
      else:
        # We must initialize the streams using this first line
        # The first two columns are "startTime, endTime"
        values[0:2] = []
        
        self.initializeStreams(values)
  
  def initializeStreams(self, values):
    streamNamePattern = re.compile(r'^([^\(]+) \(([a-z]+)\)$')
    
    for value in values:
      print "newStream : %s"%value
      streamName, type = streamNamePattern.search(value).groups()
      
      self.streams.append(self.newStream(streamName, type))

  def insertIntoStreams(self, values):
    (startTime, endTime) = values[0:2]
    values[0:2] = []
    
    for stream, value in zip(self.streams, values):
      stream[startTime:endTime] = value

import csv

class CSVStreamLoader(StreamLoader):
  def initIterable(self):
    self.iterable = csv.reader(self.file, delimiter=';')

class CSVMillisecondTimeStreamLoader(CSVStreamLoader):
  def insertIntoStreams(self, values):
    values[0] = int(values[0]) / 1000
    values[1] = int(values[1]) / 1000
    super(CSVMillisecondTimeStreamLoader, self).insertIntoStreams(values)
  
